/**
 * @作者 faner
 * @创建时间 2021/1/15 15:17
 */
package com.faner.fast.security.component;

import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONUtil;
import com.faner.fast.constant.CommonConstants;
import com.faner.fast.exception.FailedException;
import com.faner.fast.exception.HttpException;
import com.faner.fast.security.exception.ForbiddenException;
import com.faner.fast.util.R;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 授权拒绝处理器，覆盖默认的OAuth2AccessDeniedHandler 包装失败信息到HttpException
 * 自定义返回结果：没有权限访问时
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class RestfulAccessDeniedHandler extends OAuth2AccessDeniedHandler {

    private final ObjectMapper objectMapper;

    /**
     * 授权拒绝处理，使用R包装
     * @param request request
     * @param response response
     * @param e authException
     */
    @SneakyThrows
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) {

//        response.setHeader("Access-Control-Allow-Origin", "*");
//        response.setHeader("Cache-Control","no-cache");
//        response.setCharacterEncoding("UTF-8");
//        response.setContentType(CommonConstants.CONTENT_TYPE);
//        response.getWriter().println(JSONUtil.parse(R.forbidden(e.getMessage())));
//        response.getWriter().flush();
        log.info("授权失败，禁止访问 {}", request.getRequestURI());
        response.setCharacterEncoding(CommonConstants.UTF8);
        response.setContentType(CommonConstants.CONTENT_TYPE);
        R<HttpException> result = R.failed(new HttpException("授权失败，禁止访问"));
        response.setStatus(HttpStatus.HTTP_FORBIDDEN);
        PrintWriter printWriter = response.getWriter();
        printWriter.append(objectMapper.writeValueAsString(result));
    }
}
